package club.beimeng.controller;

import club.beimeng.entity.Book;
import club.beimeng.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(Model model){
        List<Book> bookList = bookService.getAllBooks();
        model.addAttribute("bookList",bookList);
        return "allBook";
    }

    @RequestMapping(value = {"addOrUpdateBook/{id}","addOrUpdateBook"})
    public String addOrUpdateBook(@PathVariable(required = false,value = "id") Integer id,Model model){
        System.out.println("id = " + id);
        if (id!=null) {
            Book book = bookService.getBookById(id);
            model.addAttribute("book",book);
        }
        return "addOrUpdate";
    }

    @RequestMapping(value = {"addOrUpdate/{id}","addOrUpdate"})
    public String addOrUpdate(@PathVariable(required = false,value = "id") Integer id,Book book){
        System.out.println("BookController.addOrUpdate");
        System.out.print("id = " + id);
        if (id != null){
            System.out.print("更新图书 - ");
            book.setBook_id(id);
            bookService.updateBookById(book);
        }else {
            System.out.print("添加图书 - ");
            bookService.addBook(book);
        }
        System.out.println(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping(value = {"delete/{id}"})
    public String delete(@PathVariable(required = false,value = "id") Integer id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

}
